package com.xnx.bincker.leader;

import com.sun.javadoc.Doclet;
import com.sun.javadoc.LanguageVersion;
import com.sun.javadoc.RootDoc;
import com.sun.tools.javadoc.Main;
import com.xnx.bincker.leader.utils.StringUtils;
import lombok.Getter;
import lombok.NonNull;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

@Component
public class JavaDocUtils extends Doclet {
//    java程序相对路径
    private static final String JAVA_RESOURCE_PATH = "src" + File.separator + "main" + File.separator + "java" + File.separator;
    private static ThreadLocal<RootDoc> rootDocThreadLocal = new ThreadLocal<>();
    @Getter
    private RootDoc rootDoc;

    public JavaDocUtils(String[] classPath, String[] sourcePath, String packageName) {
        init(classPath, sourcePath, packageName);
    }

    public JavaDocUtils(String[] sourcePath, String packageName) {
        String[] classPath = Optional.ofNullable(System.getProperty("java.class.path"))
                .orElse("")
                .split(File.pathSeparator);
        init(classPath, sourcePath, packageName);
    }

    public JavaDocUtils(String packageName) {
        this(new String[]{JAVA_RESOURCE_PATH}, packageName);
    }

    public JavaDocUtils(){
        this("com.xnx.bincker.leader");
    }
    /**
     * 获取rootdoc
     * @param classPath 依赖路径
     * @param sourcePath 源码路径
     * @param packageName 包名
     */
    private void init(String[] classPath, String[] sourcePath,@NonNull String packageName){
        List<String> args = new LinkedList<>();
        args.add("-private");
        args.add("-doclet");
        args.add(JavaDocUtils.class.getName());
        if(classPath != null && classPath.length > 0){
            args.add("-classpath");
            args.add(String.join(File.pathSeparator, classPath));
        }
        if(sourcePath != null && sourcePath.length > 0){
            args.add("-sourcepath");
            args.add(String.join(":", sourcePath));
        }
        args.add("-subpackages");
        args.add(packageName);
        args.add("-encoding");
        args.add("utf-8");
        Main.execute(args.toArray(new String[]{}));
        RootDoc rootDoc = rootDocThreadLocal.get();
        assert rootDoc != null;
        this.rootDoc = rootDoc;
    }

    /**
     * 当RootDoc初始化完成时，外部程序会吧初始化完成的RootDoc传入程序内使用
     */
    @SuppressWarnings("unused")
    public synchronized static boolean start(RootDoc rootDoc){
        rootDocThreadLocal.set(rootDoc);
        return true;
    }

    @SuppressWarnings("unused")
    public static LanguageVersion languageVersion(){
        return LanguageVersion.JAVA_1_5;
    }
}
